<!-- 添加采购订单 -->
<template>
  <el-dialog
    v-model="visibility"
    title="采购链路-节点信息修改"
    append-to-body
    width="60%"
    draggable
    :close-on-click-modal="false">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      :label-width="config.form.label.width"
      status-icon>
      <el-row>
        <el-col
          :span="12"
          class="el_col_fit">
          <el-form-item
            label="简称"
            prop="nodeRelationId">
            <el-select
              v-model="formData.nodeRelationId"
              :placeholder="purchaseNodeType[formData.nodeTypeEnum]"
              @change="change"
              clearable>
              <el-option
                v-for="val in getSimpleNameList(formData.nodeTypeEnum)"
                :key="val.id"
                :disabled="val.disabled"
                :label="val.simple_name"
                :value="val.id" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col
          :span="12"
          class="el_col_fit">
          <el-form-item
            label="资方预付款率(%)"
            prop="capitalFirstPayPercent">
            <el-input-number
              v-model="formData.capitalFirstPayPercent"
              placeholder="资方预付款率"
              controls-position="right"
              :precision="2"
              :min="0"
              :max="100">
            </el-input-number>
          </el-form-item>
        </el-col>
        <el-col
          :span="12"
          class="el_col_fit">
          <el-form-item
            label="付款方式"
            prop="capitalFirstPayWayEnum">
            <el-select
              v-model="formData.capitalFirstPayWayEnum"
              placeholder="付款方式"
              clearable>
              <el-option
                v-for="val in FirstPayWay"
                :key="val.value"
                :label="val.label"
                :value="val.value" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col
          :span="12"
          class="el_col_fit">
          <el-form-item
            label="我司预付款率(%)"
            prop="companyFirstPayPercent">
            <el-input-number
              v-model="formData.companyFirstPayPercent"
              placeholder="我司预付款率"
              controls-position="right"
              :precision="2"
              :min="0"
              :max="100">
            </el-input-number>
          </el-form-item>
        </el-col>
        <el-col
          :span="12"
          class="el_col_fit">
          <el-form-item
            label="台账编号"
            prop="billNumber">
            <el-input
              v-model="formData.billNumber"
              placeholder="台账编号"></el-input>
          </el-form-item>
        </el-col>
        <el-col
          :span="12"
          class="el_col_fit">
          <el-form-item
            label="资方尾款率(%)"
            prop="capitalEndPayPercent">
            <el-input-number
              v-model="formData.capitalEndPayPercent"
              placeholder="资方尾款率"
              controls-position="right"
              :precision="2"
              :min="0"
              :max="100">
            </el-input-number>
          </el-form-item>
        </el-col>
        <el-col
          :span="12"
          class="el_col_fit">
          <el-form-item
            label="链路单价(元)"
            prop="nodeUnitPrice">
            <el-input-number
              v-model="formData.nodeUnitPrice"
              placeholder="链路单价"
              controls-position="right"
              :precision="2"
              :min="0">
            </el-input-number>
          </el-form-item>
        </el-col>
        <el-col
          :span="12"
          class="el_col_fit">
          <el-form-item
            label="日化率(%)"
            prop="dailyChemicalRate">
            <el-input-number
              v-model="formData.dailyChemicalRate"
              placeholder="日化率"
              controls-position="right"
              :precision="4"
              :min="0"
              :max="100">
            </el-input-number>
          </el-form-item>
        </el-col>
        <el-col
          :span="12"
          class="el_col_fit">
          <el-form-item label="附件">
            <UploadFile
              ref="uploadRef"
              :show="true"
              :file-uuids="fileDataList"
              @success="success"
              @delete-file="deleteFile" />
          </el-form-item>
        </el-col>
        <el-col
          :span="12"
          class="el_col_fit">
          <el-form-item label="仓储费">
            <el-button
              type="primary"
              @click="editStorageChargesEvent">
              仓储费
            </el-button>
            <el-icon
              v-if="formData.name"
              size="20"
              color="#67c23a">
              <CircleCheckFilled />
            </el-icon>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <template #footer>
      <div>
        <el-button @click="visibility = false">{{ config.button.text.close }}</el-button>
        <el-button
          v-if="props.quoteInfo.isQuote"
          @click="quoteRate">
          引用比率
        </el-button>
        <el-button
          type="primary"
          @click="saveEvent">
          {{ config.button.text.save }}
        </el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 仓储费新增修改 -->
  <sonEdit
    ref="sonEditRef"
    :sonRowData="sonRowData"
    :quoteInfo="props.quoteInfo"
    @son-save="sonSave" />
</template>

<script setup>
import { ref, watch, nextTick } from "vue";
import config from "@/common/element-plus/config";
import ApiBaseCompany from "@/api/modules/base-company"
import ApiBaseCapitalParty from "@/api/modules/base-capital-party"
import ApiBaseRiceBarn from "@/api/modules/base-rice-barn"
import UploadFile from "@/components/UploadFile.vue"
import SonEdit from "@/views/capital-ware-house-information/component/sonEdit.vue"
import { useValidator } from "@/hooks/useValidator";
import message from "@/common/element-plus/message";
import { purchaseNodeType, FirstPayWay } from "@/common/enum/purchase-order";
import { useRoute } from "vue-router"
import ApiPurchaseOrderNode from "@/api/modules/purchase-order-node"
import ApiCapitalWareHouse from "@/api/modules/capital-ware-house"

// 路由
const route = useRoute()
// 公司简称列表
const companyList = ref([])
// 资金方简称列表
const capitalPartyList = ref([])
// 米厂简称列表
const riceBarnList = ref([])
// 附件回显
const fileDataList = ref([]);
// 表单
const formData = ref({})
// 仓储费
const sonEditRef = ref()
// 仓储费每行数据
const sonRowData = ref({})
// 显示隐藏
const visibility = ref(false)
const { required, validate, clearValidate } = useValidator()
const formRef = ref()
const formRules = {
  nodeRelationId: [required("简称", "change")],
  capitalFirstPayWayEnum: [required("付款方式", "change")],
}

// props
const props = defineProps(["rowData", "quoteInfo"])
// emits
const emits = defineEmits(["save"])

watch(() => visibility.value, async (val) => {
  if (val) {
    formData.value = props.rowData
    fileDataList.value = []
    if (formData.value.fileDataJson && Array.isArray(JSON.parse(formData.value.fileDataJson))) {
      fileDataList.value = JSON.parse(formData.value.fileDataJson);
    }
    // 公司简称列表
    let data = await ApiBaseCompany.getSimpleNameList()
    companyList.value = data.data
    // 资金方简称列表
    data = await ApiBaseCapitalParty.getSimpleNameList()
    capitalPartyList.value = data.data
    // 米厂简称列表
    data = await ApiBaseRiceBarn.getSimpleNameList()
    riceBarnList.value = data.data
    nextTick(() => {
      clearValidate(formRef.value)
    })
  }
})

// 转化为中文值
const change = (val) => {
  formData.value.nodeRelationName = getSimpleNameList(formData.value.nodeTypeEnum).find(item => item.id === val).simple_name
}

// 引用比率
const quoteRate = async () => {
  const data = await ApiCapitalWareHouse.selectById(props.quoteInfo.baseCapitalWarehouseId)
  formData.value.dailyChemicalRate = data.data.dailyChemicalRate
  formData.value.capitalEndPayPercent = data.data.capitalEndPayPercent
  formData.value.companyFirstPayPercent = data.data.companyFirstPayPercent
  formData.value.capitalFirstPayPercent = data.data.capitalFirstPayPercent
}

// 保存
const saveEvent = async () => {
  await validate(formRef.value)
  if (route.query.purchaseOrderNumber) {
    formData.value.baseCapitalWarehouseCostRuleName = formData.value.name
    await ApiPurchaseOrderNode.update(formData.value)
  }
  emits("save", formData.value)
  visibility.value = false
}

// 根据不同枚举获取节点列表简称
const getSimpleNameList = (data) => {
  if (Object.keys(purchaseNodeType)[0] === data) {
    const find = riceBarnList.value.find(item => item.id === formData.value.nodeRelationId)
      if (!find && formData.value.nodeRelationId) riceBarnList.value.push({
        simple_name: formData.value.nodeRelationName + "(已禁用)",
        id: formData.value.nodeRelationId,
        disabled: true
      })
    return riceBarnList.value
  }
  if (Object.keys(purchaseNodeType)[1] === data || Object.keys(purchaseNodeType)[4] === data) {
    const find = capitalPartyList.value.find(item => item.id === formData.value.nodeRelationId)
      if (!find && formData.value.nodeRelationId) capitalPartyList.value.push({
        simple_name: formData.value.nodeRelationName + "(已禁用)",
        id: formData.value.nodeRelationId,
        disabled: true
      })
    return capitalPartyList.value
  }
  if (Object.keys(purchaseNodeType)[2] === data || Object.keys(purchaseNodeType)[3] === data) {
    const find = companyList.value.find(item => item.id === formData.value.nodeRelationId)
      if (!find && formData.value.nodeRelationId) companyList.value.push({
        simple_name: formData.value.nodeRelationName + "(已禁用)",
        id: formData.value.nodeRelationId,
        disabled: true
      })
    return companyList.value
  }
}

// 打开仓储费对话框
const editStorageChargesEvent = () => {
  sonEditRef.value.visibility = true
  sonRowData.value = Object.assign({}, formData.value)
}

// 保存回调
const sonSave = (data) => {
  sonEditRef.value.visibility = false
  message.success()
  formData.value = { ...formData.value, ...data }
}

// 上传文件成功回调
const success = (data) => {
  const file = formData.value.fileDataJson ? JSON.parse(formData.value.fileDataJson) : []
  file.push(data)
  formData.value.fileDataJson = JSON.stringify(file)
}

// 删除文件回调
const deleteFile = (data) => {
  const file = JSON.parse(formData.value.fileDataJson)
  formData.value.fileDataJson = JSON.stringify(file.filter(item => item === data))
}

defineExpose({ visibility })
</script>

<style lang="scss">
.el-input-number {
  width: 100%;
}

.el-row {
  align-items: flex-start;
}
</style>